/*   
* Project: OSMP
* FileName: ParseHandler.java
* version: V1.0
*/
package com.jwkj.scollect.collector;

import com.jwkj.scollect.collector.ltwy.codec.impl.ModbusRTUCodec;
import com.jwkj.scollect.collector.ltwy.data._03.MultiReadRxDataGram;
import com.jwkj.scollect.collector.ltwy.data._03.MultiReadTxDataGram;
import com.jwkj.scollect.collector.ltwy.util.ByteUtils;
import com.jwkj.scollect.conf.SpringUtils;
import com.jwkj.scollect.conf.SystemGloble;
import com.jwkj.scollect.model.TblDevice;
import com.jwkj.scollect.model.TblSensor;
import com.jwkj.scollect.service.DeviceService;
import org.apache.log4j.Logger;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.List;

/**
 * Description:采集数据处理器
 *
 * @author: wangkaiping
 * @date: 2018年3月6日 下午3:36:13上午10:51:30
 */
public class ParseHandler extends Thread {
    private static Logger logger = Logger.getLogger(ParseHandler.class);
    private static ModbusRTUCodec codec = ModbusRTUCodec.getInstance();
    private Socket socket;
    private int offset = 0;
    private String ipendpoint;
    private String ip = "";
    private String port = "";
    private String dcode = "";
    private int maxTimeOut = 3;

    public ParseHandler(Socket socket) {
        if (socket == null) {
            throw new NullPointerException("socket is null");
        }
        this.socket = socket;
        ipendpoint = socket.getRemoteSocketAddress().toString();
        if (!StringUtils.isEmpty(ipendpoint)) {
            String[] ips = ipendpoint.replaceAll("/", "").split(":");
            ip = ips[0];
            port = ips[1];
        }
        dcode = SystemGloble.getParam(SystemGloble.COLLECTOR_CODE);
        logger.debug("----------------新的客户端连接 IP：" + ip + " PORT: " + port + " ----------");
    }

    public void run() {
        int timeOutIndex = 0;
        try {
            socket.setSoTimeout(10000);
        } catch (SocketException e2) {
            logger.error("socket connecte failed", e2);
        }
        while (!socket.isClosed() && socket.isConnected()) {
            byte[] buffer = new byte[2048];
            int len = 0;
            MultiReadTxDataGram tx = new MultiReadTxDataGram(0x01, 0x0000, 0x000a);
            byte[] cmd = codec.encode(tx);
            try {
                socket.getOutputStream().write(cmd);
                try {
                    len = socket.getInputStream().read(buffer, 0, buffer.length);
                } catch (SocketTimeoutException e) {
                    if (timeOutIndex >= maxTimeOut) { //连接超时大于3次结束socket连接
                        socket.close();
                        break;
                    } else {
                        ++timeOutIndex;
                        logger.error("time-out for get socket data and timeOutIndex: " + timeOutIndex, e);
                        continue;
                    }
                }
                byte[] result = new byte[len];
                for (int i = 0; i < result.length; i++) {
                    result[i] = buffer[i];
                }
                try {
                    MultiReadRxDataGram rx = new MultiReadRxDataGram(result);
                    logger.debug("设备反馈报文:" + ByteUtils.parseByte2HexStr(rx.toBytes()));
                    int [] datas = rx.getRegDatas();
                    for(int i : datas){
                        logger.debug("-----------读取到的数据 " + i);
                    }
                } catch (Exception e) {
                    logger.error("modbus 解析错误", e);
                }
            } catch (IOException e) {
                logger.error("socket connect error", e);
                try {
                    socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
                logger.error(e.getMessage(), e);
            }
        }
        logger.error("客户端 连接断开 ip:" + ip + " port:" + port);
    }

    private String getDeviceId(int address) {
        DeviceService deviceService = SpringUtils.getBean(DeviceService.class);
        TblDevice device = deviceService.getDevicesByAddress(address);
        if (null != device) {
            return device.getId();
        }
        return null;
    }

    private List<TblSensor> getSensor(String deviceId) {
        DeviceService deviceService = SpringUtils.getBean(DeviceService.class);
        List<TblSensor> sensors = deviceService.getSensorByDid(deviceId);
        return sensors;
    }

    public static void main(String[] args) {
        MultiReadTxDataGram tx = new MultiReadTxDataGram(0x01, 0x0000, 0x000a);
        byte[] cmd = codec.encode(tx);
        System.out.println(ByteUtils.parseByte2HexStr(cmd));
    }

}
